/**
 * 
 */
package com.zprmb.udzt;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;
import com.zprmb.udzt.bean.Regist;
import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.ll.BaseHelper;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.Regular;
import com.zprmb.udzt.util.ToJSON;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.vo.AuthFailureError;
import com.zprmb.udzt.vo.Request.Method;
import com.zprmb.udzt.vo.RequestQueue;
import com.zprmb.udzt.vo.Response;
import com.zprmb.udzt.vo.VolleyError;
import com.zprmb.udzt.vo.toolbox.HttpClientStack;
import com.zprmb.udzt.vo.toolbox.HttpStack;
import com.zprmb.udzt.vo.toolbox.ImageRequest;
import com.zprmb.udzt.vo.toolbox.JsonObjectRequest;
import com.zprmb.udzt.vo.toolbox.Volley;

/**
 * 注册
 */
public class RegisteredActivity extends BaseActivity implements OnClickListener{
	private TextView tv_user_phone,tv_registinfo;
	private ImageView img_back,img_captcha,pass;
	private TimeCount timeCount;
	private Button btn_send_mes,btn_register;
	private String csrf;
	private String mobile;
	private EditText et_imgCaptcha,et_codes,et_pwd,et_tuijian;
	private CheckBox checkBox;
	private List<Regist> list=new ArrayList<Regist>();
	private RequestQueue mQueue;
	private RelativeLayout rl_back;
	private TextView tv_customer;
	private String channel;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regist_layout);
		 BbtApplication.getInstance().addActvity(this);
		DefaultHttpClient httpclient = new DefaultHttpClient();
        CookieStore cookieStore = new BasicCookieStore();
        httpclient.setCookieStore(cookieStore);
        HttpStack httpStack = new HttpClientStack(httpclient);        
        UmengDate("1");
//        Log.e("渠道注册"," msg="+getMetaData(this));
//        Log.e("渠道2", getChannelName(getAppMetaData(RegisteredActivity.this, "UMENG_CHANNEL")));
        mQueue = Volley.newRequestQueue(this, httpStack);
		tv_user_phone=(TextView)findViewById(R.id.user_phone);
		img_back=(ImageView)findViewById(R.id.img_back);
		pass=(ImageView)findViewById(R.id.img_pass);
		img_captcha=(ImageView)findViewById(R.id.img_captcha);
		tv_registinfo=(TextView)findViewById(R.id.regist_info);
		btn_send_mes=(Button)findViewById(R.id.btn_send_mes);
		btn_register=(Button)findViewById(R.id.btn_register);
		checkBox=(CheckBox)findViewById(R.id.check);
		et_imgCaptcha=(EditText)findViewById(R.id.regist_captcha);
		et_codes=(EditText)findViewById(R.id.regist_codes);
		et_pwd=(EditText)findViewById(R.id.regist_pwd);
		et_tuijian=(EditText)findViewById(R.id.regist_recommend);
		rl_back=(RelativeLayout)findViewById(R.id.rl_back);
		tv_customer=(TextView)findViewById(R.id.enterprise_tel);

		tv_customer.setOnClickListener(this);
		rl_back.setOnClickListener(this);
		img_back.setOnClickListener(this);
		img_captcha.setOnClickListener(this);
		pass.setOnClickListener(this);
		
		tv_registinfo.setOnClickListener(this);
		btn_send_mes.setOnClickListener(this);
		checkBox.setOnClickListener(this);
		btn_register.setOnClickListener(this);
		et_pwd.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if(et_pwd.getText().toString().equals("")){
					pass.setVisibility(View.GONE);
				}else{
					pass.setVisibility(View.VISIBLE);
				}
			}
		});
	 mobile=getIntent().getStringExtra("phone");
		
		tv_user_phone.setText(mobile);
		initcaptcha();
		timeCount=new TimeCount(60000, 100);
		
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		BbtApplication.getInstance().removeActvity(this);
	}
	
	public  String getMetaData(Context context) {
		
		PackageManager packageManager = context.getPackageManager();
		ApplicationInfo applicationInfo;
		try {
			applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
			if (applicationInfo != null && applicationInfo.metaData != null) {
				channel =  String.valueOf(applicationInfo.metaData.get("UMENG_CHANNEL")); 
				
			}
		} catch (NameNotFoundException e) {
			throw new RuntimeException(
					"you must set " + "" + " and " + "" + "  in your manifest file.", e);
		}

		return channel;
	}
	private void initcaptcha() {
		// TODO Auto-generated method stub
		ImageRequest imageRequest = new ImageRequest(  
				Constant.URL+"/captcha.png",  
		        new Response.Listener<Bitmap>() {  
		            @Override  
		            public void onResponse(Bitmap response) {  
		                img_captcha.setImageBitmap(response);  
		            }  
		        }, 0, 0, Config.RGB_565, new Response.ErrorListener() {  
		            @Override  
		            public void onErrorResponse(VolleyError error) {  
		                img_captcha.setImageResource(R.drawable.bbt_bg);  
		            }  
		        }); 
		mQueue.add(imageRequest);
		
	}
	private void initData() {
		// 这个接口返回的请求头里有3个参数，，前两个暂时写死！
		VolleryUtil vollery=new VolleryUtil() {
			 
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				try {
					
					if (jsonObject.optInt("success") == 1) {
						csrf = jsonObject.getJSONObject("data").optString(
								"csrf");
						initmessage();
					} else {
						
						Toast.makeText(RegisteredActivity.this,
								jsonObject.optString("comment"), 0).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				
			}
		};
		vollery.setHeaders("appId", "bbt3.0:android");
		vollery.setHeaders("appSecret", "RH89xcYh");
		vollery.setHeaders("appVersion", getAppVersion());
		vollery.setRequestMethod(1);
		
		vollery.execute(this, Constant.URL + "api/csrf", "");
	}
	private void initmessage(){
		String capt=et_imgCaptcha.getText().toString();
	AjaxParams params=new AjaxParams();
	
		params.put("imgCaptcha", capt);
	 
	params.put("mobile", mobile);
	JsonObjectRequest json = new JsonObjectRequest(Method.GET,
			Constant.URL+"/api/v5/register/sendMobileCaptcha?"+params.toString(), null, new Response.Listener<JSONObject>() {
				public void onResponse(JSONObject response) {
					Log.e("短信", response.toString());
					if(response.optInt("success")==1){
						
						timeCount.start();
					}else{
						Toast.makeText(RegisteredActivity.this,response.optString("comment") , 2000).show();
					}
				}
			}, new Response.ErrorListener() {
				public void onErrorResponse(VolleyError error) {
					
					
				}
			}) { 
		public Map<String, String> getHeaders() throws AuthFailureError {
			HashMap<String, String> headers = new HashMap<String, String>();  
			headers.put("csrf", csrf);
			return headers;
		}
	};
	mQueue.add(json);

	

	
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.img_back:
			finish();
			break;
		case R.id.img_captcha:
			initcaptcha();
			break;
		case R.id.btn_send_mes:
			if(et_imgCaptcha.getText().toString().equals("")){
				Toast.makeText(RegisteredActivity.this, "请先输入图形验证码", 2000).show();
			}else{
				
				initData();
				
			}
			break;
		case R.id.check:
			 if(checkBox.isChecked()){
				 btn_register.setBackgroundResource(R.drawable.my_button);
			 }else{
				 btn_register.setBackgroundResource(R.drawable.btn_unclick);
			 }
			break;
		case R.id.btn_register:
			if(et_imgCaptcha.getText().toString().equals("")){
				Toast.makeText(RegisteredActivity.this, "请先输入图形验证码", 2000).show();
				return;
			}
			if(et_codes.getText().toString().equals("")){
				Toast.makeText(RegisteredActivity.this, "请先输入短信验证码", 2000).show();
				return;
			}
			if(et_pwd.getText().toString().equals("")){
				Toast.makeText(RegisteredActivity.this, "请先输入密码", 2000).show();
				return;
			}
//			if(Regular.isMobileNO(et_tuijian.getText().toString())){
//				Toast.makeText(RegisteredActivity.this, "请先输入正确的推荐人手机号", 2000).show();
//				return;
//			}
			if(!Regular.getPass(et_pwd.getText().toString().trim())){
				Toast.makeText(RegisteredActivity.this, "“登录密码可以为6-16位字符，可使用字母且分区大小写、数字、下划线且不包含空格”", 2000).show();
				return;
			}
			btn_register.setBackgroundResource(R.drawable.btn_unclick);
			btn_register.setEnabled(false);
			  register();
			break;
		case R.id.regist_info:
			Intent intent2=new Intent(RegisteredActivity.this,V4WebViewActivity.class);
			intent2.putExtra("url", "/FE/about/agreement?app=true");
			intent2.putExtra("title", "优点智投平台服务协议");
			startActivity(intent2);
			break;
		case R.id.img_pass:
			if(et_pwd.getTransformationMethod().equals(PasswordTransformationMethod  
                    .getInstance())){
				et_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
				pass.setBackgroundResource(R.drawable.yan1);
			}else{
				et_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
				pass.setBackgroundResource(R.drawable.yan2);
			}
			break;
		case R.id.rl_back:
			finish();
			break;
		case R.id.enterprise_tel:
			BaseHelper.showDialog2(this, "拨号", "400-0101-016", 1);
			break;
		}
	}
	
	private void register() {
		// TODO Auto-generated method stub
		AjaxParams params=new AjaxParams();
		params.put("mobile", mobile);
		params.put("password", et_pwd.getText().toString());
		params.put("captcha", et_codes.getText().toString());
		params.put("ref", et_tuijian.getText().toString());
		params.put("appVersion", getAppVersion());
		try {
			params.put("platform", URLDecoder.decode(getMetaData(RegisteredActivity.this),"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		VolleryUtil volleryUtil=new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				btn_register.setBackgroundResource(R.drawable.my_button);
				btn_register.setEnabled(true);
				// TODO Auto-generated method stub
				Log.e("注册", jsonObject.toString());
				ToJSON.initData(jsonObject.toString());
				if(jsonObject.optInt("success")==1){
					JSONObject json1=jsonObject.optJSONObject("data");
					Gson gson=new Gson();
					Editor editor = getShare().edit();
					editor.putString(
							"token",
							json1.optString(
									"token"));
					editor.putString(
							"mobile",
							json1.optString(
									"mobile"));
					editor.putString(
							"userId",
							json1.optString(
									"userId"));
					editor.putString(
							"usercode",
							json1.optString(
									"userCode"));
					editor.commit();
					list=gson.fromJson(json1.optString("propsList"), new TypeToken<ArrayList<Regist>>() {
					}.getType());
					Intent intent=new Intent(RegisteredActivity.this,Register_Success.class);
//					intent.putExtra("registerType",json1.optString(
//							"registerType"));
//					intent.putExtra("resume", json1.optString(
//							"authenticationAmount"));
					
					intent.putExtra("tiyan", list.get(0).getEXPERIENCE_CASH());
//					intent.putExtra("red",json1.optString(
//							"bonusAmount"));					
					startActivity(intent);
					RegisteredActivity.this.finish();
				}else{
					Toast.makeText(RegisteredActivity.this, jsonObject.optString("comment"), 2000).show();
				} 
				
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				btn_register.setBackgroundResource(R.drawable.my_button);
				btn_register.setEnabled(true);
			}
		};
		volleryUtil.setRequestMethod(0);
		volleryUtil.setShow(true);
		volleryUtil.setHeaders("client", "android");
		volleryUtil.setHeaders("deviceToken", getdevice_token());
		volleryUtil.execute(RegisteredActivity.this, Constant.
				URL+"/api/v5/register/mobileRegister?", params.toString());
//		 Toast.makeText(RegisteredActivity.this, getMetaData(RegisteredActivity.this), 2000).show();
	}
	public static String getAppMetaData(Context ctx, String key) {  
	      if (ctx == null || TextUtils.isEmpty(key)) {  
	          return null;  
	      }  
	      String resultData = null;  
	      try {  
	          PackageManager packageManager = ctx.getPackageManager();  
	          if (packageManager != null) {  
	              ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);  
	              if (applicationInfo != null) {  
	                  if (applicationInfo.metaData != null) {  
	                      resultData = applicationInfo.metaData.getString(key);  
	                  }  
	              }  
	  
	          }  
	      } catch (NameNotFoundException e) {
	          e.printStackTrace();  
	      }  
	  
	      return resultData;  
	  }
	private void UmengDate(String what) {
		try {
			ApplicationInfo appInfo = this.getPackageManager()
					.getApplicationInfo(getPackageName(),
							PackageManager.GET_META_DATA);
			String msg = appInfo.metaData.getString("UMENG_CHANNEL");
			Map<String, String> m = new HashMap<String, String>();
			m.put(msg, msg);
			MobclickAgent.onEventValue(this, what, m,
					1);
			Log.e("渠道1","msg="+msg);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}
	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
		super(millisInFuture, countDownInterval);
		}

		@Override
		public void onFinish() {// 计时完毕
			btn_send_mes.setText("重新获取");
			btn_send_mes.setBackgroundResource(R.drawable.my_button);
			btn_send_mes.setClickable(true);
		}
   
		@Override
		public void onTick(long millisUntilFinished) {// 计时过程
			btn_send_mes.setClickable(false);//防止重复点击
			btn_send_mes.setBackgroundResource(R.drawable.btn_unclick);
			btn_send_mes.setText(millisUntilFinished / 1000 + "s后重新获取");
		}
	}
	

}
